import { FC, ReactElement, useCallback, useState } from "react";
import { Container } from "./styled";

interface IProps {
  changeImage: (file: File) => void;
}

const ImageSelect: FC<IProps> = ({ changeImage }): ReactElement => {
  const [image, setImage] = useState("");

  const handleChange = useCallback(
    (event) => {
      const reader = new FileReader();
      const AllowImgFileSize = 2100000; //上传图片最大值(单位字节)（ 2 M = 2097152 B ）超过2M上传失败
      const file = event.target.files[0];

      if (file && file.size < AllowImgFileSize) {
        reader.onload = function (evt) {
          const { result }: any = evt.target;
          setImage(result);
          //! formData 需要上传 File对象 也就是文件 而不是 读取后img可以显示的base64 base64后台拿到按字符串处理
          changeImage(file);
        };
        reader.readAsDataURL(file);
      } else {
        console.log("图片大小不得大于2M");
      }
    },
    [changeImage]
  );

  return (
    <Container>
      <input type="file" onChange={handleChange} />
      <img src={image} alt="" />
    </Container>
  );
};

export default ImageSelect;
